# PowerShell脚本：自动更新TypeScript接口
# 使用方法：在PowerShell中运行 .\generate-types.ps1

Write-Host "🚀 开始更新TypeScript接口..." -ForegroundColor Green

# 检查后端服务是否运行
$backendUrl = "http://localhost:8080/v3/api-docs"
try {
    $response = Invoke-RestMethod -Uri $backendUrl -Headers @{ "Accept" = "application/json;charset=UTF-8" } -TimeoutSec 5
    Write-Host "✅ 后端服务正常运行" -ForegroundColor Green
} catch {
    Write-Host "❌ 无法连接到后端服务，请确保后端运行在 http://localhost:8080" -ForegroundColor Red
    Write-Host "错误信息: $($_.Exception.Message)" -ForegroundColor Yellow
    exit 1
}

# 获取最新的API文档
Write-Host "📥 正在获取最新的API文档..." -ForegroundColor Yellow
try {
    Invoke-RestMethod -Uri $backendUrl -Headers @{ "Accept" = "application/json;charset=UTF-8" } | 
    ConvertTo-Json -Depth 10 | 
    Out-File -FilePath "api-docs.json" -Encoding UTF8 -Force
    Write-Host "✅ API文档已更新" -ForegroundColor Green
} catch {
    Write-Host "❌ 获取API文档失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

# 生成TypeScript接口
Write-Host "🔧 正在生成TypeScript接口..." -ForegroundColor Yellow
try {
    npx @hey-api/openapi-ts -i ./api-docs.json -o src/api -c @hey-api/client-fetch
    Write-Host "✅ TypeScript接口生成成功" -ForegroundColor Green
} catch {
    Write-Host "❌ 生成TypeScript接口失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

Write-Host "🎉 所有操作完成！" -ForegroundColor Green
Write-Host "📁 生成的文件位于: src/api/" -ForegroundColor Cyan